<template>
  <div class="workflow-designer">
    <div class="toolbar">
      <el-button type="primary" @click="saveWorkflow">保存流程</el-button>
      <el-button @click="loadWorkflow">加载流程</el-button>
      <el-button @click="exportWorkflow">导出流程</el-button>
      <el-button @click="clearCanvas">清空画布</el-button>
      <el-button @click="previewWorkflow">预览流程</el-button>
      <el-button 
        type="danger" 
        @click="deleteSelectedElement"
        :disabled="!selectedNode"
      >
        <el-icon><Delete /></el-icon>
        删除选中
      </el-button>
    </div>
    
    <div class="main-content">
      <!-- 左侧工具栏 -->
      <div class="toolbox" :class="{ 'collapsed': leftCollapsed }">
        <div class="toolbox-header">
          <h3>流程节点</h3>
          <el-button 
            type="text" 
            @click="toggleLeftPanel"
            class="collapse-btn"
          >
            <el-icon><component :is="leftCollapsed ? 'Expand' : 'Fold'" /></el-icon>
          </el-button>
        </div>
        
        <div class="toolbox-content" v-show="!leftCollapsed">
          <!-- 基础节点 -->
          <div class="node-category">
            <h4>基础节点</h4>
            <div class="node-types">
              <div 
                v-for="nodeType in basicNodeTypes" 
                :key="nodeType.type"
                class="node-item"
                draggable="true"
                @dragstart="onDragStart($event, nodeType)"
              >
                <el-icon><component :is="nodeType.icon" /></el-icon>
                <span>{{ nodeType.label }}</span>
              </div>
            </div>
          </div>
          
          <!-- 审批节点 -->
          <div class="node-category">
            <h4>审批节点</h4>
            <div class="node-types">
              <div 
                v-for="nodeType in approvalNodeTypes" 
                :key="nodeType.type"
                class="node-item"
                draggable="true"
                @dragstart="onDragStart($event, nodeType)"
              >
                <el-icon><component :is="nodeType.icon" /></el-icon>
                <span>{{ nodeType.label }}</span>
              </div>
            </div>
          </div>
          
          <!-- 控制节点 -->
          <div class="node-category">
            <h4>控制节点</h4>
            <div class="node-types">
              <div 
                v-for="nodeType in controlNodeTypes" 
                :key="nodeType.type"
                class="node-item"
                draggable="true"
                @dragstart="onDragStart($event, nodeType)"
              >
                <el-icon><component :is="nodeType.icon" /></el-icon>
                <span>{{ nodeType.label }}</span>
              </div>
            </div>
          </div>
          
          <!-- 动作节点 -->
          <div class="node-category">
            <h4>动作节点</h4>
            <div class="node-types">
              <div 
                v-for="nodeType in actionNodeTypes" 
                :key="nodeType.type"
                class="node-item"
                draggable="true"
                @dragstart="onDragStart($event, nodeType)"
              >
                <el-icon><component :is="nodeType.icon" /></el-icon>
                <span>{{ nodeType.label }}</span>
              </div>
            </div>
          </div>
          
          <h3>审批人类型</h3>
          <div class="approver-types">
            <el-radio-group v-model="selectedApproverType">
              <el-radio label="user">指定人员</el-radio>
              <el-radio label="department">部门负责人</el-radio>
              <el-radio label="role">指定角色</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      
      <!-- 中间画布 -->
      <div class="canvas-area">
        <VueFlow
          v-model="elements"
          :default-viewport="{ zoom: 1 }"
          :min-zoom="0.2"
          :max-zoom="4"
          class="workflow-canvas"
          @connect="onConnect"
          @node-click="onNodeClick"
          @dragover="onDragOver"
          @drop="onDrop"
        >
          <Background />
          <MiniMap />
          <Controls />
          <!-- 节点插槽保持不变 -->
          <template #node-start="nodeProps">
            <StartNode v-bind="nodeProps" />
          </template>
          <template #node-approval="nodeProps">
            <ApprovalNode v-bind="nodeProps" />
          </template>
          <template #node-joint-approval="nodeProps">
            <JointApprovalNode v-bind="nodeProps" />
          </template>
          <template #node-add-approval="nodeProps">
            <AddApprovalNode v-bind="nodeProps" />
          </template>
          <template #node-reject="nodeProps">
            <RejectNode v-bind="nodeProps" />
          </template>
          <template #node-condition="nodeProps">
            <ConditionNode v-bind="nodeProps" />
          </template>
          <template #node-parallel="nodeProps">
            <ParallelNode v-bind="nodeProps" />
          </template>
          <template #node-wait="nodeProps">
            <WaitNode v-bind="nodeProps" />
          </template>
          <template #node-script="nodeProps">
            <ScriptNode v-bind="nodeProps" />
          </template>
          <template #node-email="nodeProps">
            <EmailNode v-bind="nodeProps" />
          </template>
          <template #node-timer="nodeProps">
            <TimerNode v-bind="nodeProps" />
          </template>
          <template #node-end="nodeProps">
            <EndNode v-bind="nodeProps" />
          </template>
        </VueFlow>
      </div>
      
      <!-- 右侧属性面板 -->
      <div class="properties-area" :class="{ 'collapsed': rightCollapsed }">
        <div class="properties-header">
          <h3>节点属性</h3>
          <el-button 
            type="text" 
            @click="toggleRightPanel"
            class="collapse-btn"
          >
            <el-icon><component :is="rightCollapsed ? 'Expand' : 'Fold'" /></el-icon>
          </el-button>
        </div>
        
        <div class="properties-content" v-show="!rightCollapsed">
          <div v-if="selectedNode" class="node-properties">
            <div class="node-header">
              <h4>{{ selectedNode.data.name }}</h4>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteNode(selectedNode.id)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
                删除节点
              </el-button>
            </div>
            <el-form :model="selectedNode.data" label-width="80px">
              <el-form-item label="节点名称">
                <el-input v-model="selectedNode.data.name" />
              </el-form-item>
              
              <el-form-item label="节点类型">
                <el-select v-model="selectedNode.data.type" disabled>
                  <el-option label="开始" value="start" />
                  <el-option label="审批" value="approval" />
                  <el-option label="会签" value="joint-approval" />
                  <el-option label="加签" value="add-approval" />
                  <el-option label="驳回" value="reject" />
                  <el-option label="条件" value="condition" />
                  <el-option label="结束" value="end" />
                </el-select>
              </el-form-item>
              
              <!-- 审批节点特有属性 -->
              <template v-if="selectedNode.data.type === 'approval' || selectedNode.data.type === 'joint-approval' || selectedNode.data.type === 'add-approval'">
                <el-form-item label="审批人">
                  <el-button @click="showApproverDialog = true">
                    选择审批人
                  </el-button>
                  <div v-if="selectedNode.data.approvers?.length" class="approver-list">
                    <el-tag 
                      v-for="approver in selectedNode.data.approvers" 
                      :key="approver.id"
                      closable
                      @close="removeApprover(approver)"
                    >
                      {{ approver.name }}
                    </el-tag>
                  </div>
                </el-form-item>
                
                <el-form-item label="抄送人">
                  <el-button @click="showCcDialog = true">
                    选择抄送人
                  </el-button>
                  <div v-if="selectedNode.data.ccUsers?.length" class="cc-list">
                    <el-tag 
                      v-for="cc in selectedNode.data.ccUsers" 
                      :key="cc.id"
                      closable
                      @close="removeCcUser(cc)"
                    >
                      {{ cc.name }}
                    </el-tag>
                  </div>
                </el-form-item>
              </template>
              
              <!-- 会签节点特有属性 -->
              <template v-if="selectedNode.data.type === 'joint-approval'">
                <el-form-item label="会签规则">
                  <el-radio-group v-model="selectedNode.data.jointRule">
                    <el-radio label="all">全部通过</el-radio>
                    <el-radio label="any">任一通过</el-radio>
                    <el-radio label="majority">多数通过</el-radio>
                  </el-radio-group>
                </el-form-item>
              </template>
              
              <!-- 加签节点特有属性 -->
              <template v-if="selectedNode.data.type === 'add-approval'">
                <el-form-item label="加签类型">
                  <el-radio-group v-model="selectedNode.data.addType">
                    <el-radio label="before">前置加签</el-radio>
                    <el-radio label="after">后置加签</el-radio>
                  </el-radio-group>
                </el-form-item>
              </template>
              
              <!-- 驳回节点特有属性 -->
              <template v-if="selectedNode.data.type === 'reject'">
                <el-form-item label="驳回目标">
                  <el-button @click="showRejectTargetDialog = true">
                    选择驳回目标
                  </el-button>
                  <div v-if="selectedNode.data.rejectTarget" class="reject-target">
                    <el-tag closable @close="removeRejectTarget">
                      {{ selectedNode.data.rejectTarget.name }}
                    </el-tag>
                  </div>
                </el-form-item>
              </template>
              
              <!-- 条件节点特有属性 -->
              <template v-if="selectedNode.data.type === 'condition'">
                <el-form-item label="条件表达式">
                  <el-input 
                    v-model="selectedNode.data.condition" 
                    type="textarea"
                    placeholder="请输入条件表达式，例如：amount > 1000"
                  />
                </el-form-item>
              </template>
            </el-form>
          </div>
          <div v-else class="no-selection">
            <p>请选择一个节点来编辑属性</p>
            <div class="delete-tips">
              <p>💡 删除提示：</p>
              <ul>
                <li>选中节点后点击"删除节点"按钮</li>
                <li>或使用工具栏的"删除选中"按钮</li>
                <li>或按键盘的 Delete 键</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 审批人选择对话框 -->
    <ApproverDialog 
      v-model="showApproverDialog"
      :approver-type="selectedApproverType"
      @confirm="onApproverSelected"
    />
    
    <!-- 抄送人选择对话框 -->
    <CcDialog 
      v-model="showCcDialog"
      @confirm="onCcSelected"
    />
    
    <!-- 驳回目标选择对话框 -->
    <RejectTargetDialog 
      v-model="showRejectTargetDialog"
      :nodes="elements"
      @confirm="onRejectTargetSelected"
    />
    
    <!-- 状态栏 -->
    <div class="status-bar">
      <span>节点数: {{ nodeCount }}</span>
      <span>连接数: {{ edgeCount }}</span>
      <span>缩放: {{ Math.round(zoom * 100) }}%</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, defineAsyncComponent } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import type { Node, Edge } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { MiniMap } from '@vue-flow/minimap'
import { Controls } from '@vue-flow/controls'
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import '@vue-flow/controls/dist/style.css'
import '@vue-flow/minimap/dist/style.css'
import { ElButton, ElIcon, ElRadioGroup, ElRadio, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElTag, ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Switch, CircleCheck, UserFilled, Plus, Close, Document, FolderOpened, Download, ZoomIn, ZoomOut, FullScreen, Delete, View, InfoFilled, Connection, Position, User, Share, Clock, Timer, Link, Bell, Message, Folder } from '@element-plus/icons-vue'
// 节点组件导入
const StartNode = defineAsyncComponent(() => import('./nodes/StartNode.vue'))
const ApprovalNode = defineAsyncComponent(() => import('./nodes/ApprovalNode.vue'))
const JointApprovalNode = defineAsyncComponent(() => import('./nodes/JointApprovalNode.vue'))
const AddApprovalNode = defineAsyncComponent(() => import('./nodes/AddApprovalNode.vue'))
const RejectNode = defineAsyncComponent(() => import('./nodes/RejectNode.vue'))
const ConditionNode = defineAsyncComponent(() => import('./nodes/ConditionNode.vue'))
const ParallelNode = defineAsyncComponent(() => import('./nodes/ParallelNode.vue'))
const WaitNode = defineAsyncComponent(() => import('./nodes/WaitNode.vue'))
const ScriptNode = defineAsyncComponent(() => import('./nodes/ScriptNode.vue'))
const EmailNode = defineAsyncComponent(() => import('./nodes/EmailNode.vue'))
const TimerNode = defineAsyncComponent(() => import('./nodes/TimerNode.vue'))
const EndNode = defineAsyncComponent(() => import('./nodes/EndNode.vue'))
const ApproverDialog = defineAsyncComponent(() => import('./dialogs/ApproverDialog.vue'))
const CcDialog = defineAsyncComponent(() => import('./dialogs/CcDialog.vue'))
const RejectTargetDialog = defineAsyncComponent(() => import('./dialogs/RejectTargetDialog.vue'))
import WorkflowApiService from '../services/workflowApi'
import type { FlowElement, WorkflowDefinition, WorkflowStep, User as WorkflowUser, Department, Role, CreateWorkflowRequest } from '../types/workflow'

// 定义emit
const emit = defineEmits<{
  save: [workflow: WorkflowDefinition]
  close: []
}>()

// 节点类型定义 - 扩展更多节点类型
const nodeTypes = [
  { type: 'start', label: '开始', icon: 'CircleCheck', category: 'basic' },
  { type: 'approval', label: '审批', icon: 'User', category: 'approval' },
  { type: 'joint-approval', label: '会签', icon: 'UserFilled', category: 'approval' },
  { type: 'add-approval', label: '加签', icon: 'Plus', category: 'approval' },
  { type: 'reject', label: '驳回', icon: 'Close', category: 'control' },
  { type: 'condition', label: '条件', icon: 'Switch', category: 'control' },
  { type: 'parallel', label: '并行', icon: 'Share', category: 'control' },
  { type: 'wait', label: '等待', icon: 'Clock', category: 'control' },
  { type: 'script', label: '脚本', icon: 'Document', category: 'action' },
  { type: 'email', label: '邮件', icon: 'Message', category: 'action' },
  { type: 'notification', label: '通知', icon: 'Bell', category: 'action' },
  { type: 'subprocess', label: '子流程', icon: 'Folder', category: 'action' },
  { type: 'timer', label: '定时器', icon: 'Timer', category: 'control' },
  { type: 'webhook', label: 'Webhook', icon: 'Link', category: 'action' },
  { type: 'end', label: '结束', icon: 'CircleCheck', category: 'basic' }
]

// 节点分组 - 更详细的分类
const basicNodeTypes = [
  { type: 'start', label: '开始', icon: 'CircleCheck' },
  { type: 'end', label: '结束', icon: 'CircleCheck' }
]

const approvalNodeTypes = [
  { type: 'approval', label: '审批', icon: 'User' },
  { type: 'joint-approval', label: '会签', icon: 'UserFilled' },
  { type: 'add-approval', label: '加签', icon: 'Plus' },
  { type: 'reject', label: '驳回', icon: 'Close' }
]

const controlNodeTypes = [
  { type: 'condition', label: '条件', icon: 'Switch' },
  { type: 'parallel', label: '并行', icon: 'Share' },
  { type: 'wait', label: '等待', icon: 'Clock' },
  { type: 'timer', label: '定时器', icon: 'Timer' }
]

const actionNodeTypes = [
  { type: 'script', label: '脚本', icon: 'Document' },
  { type: 'email', label: '邮件', icon: 'Message' },
  { type: 'notification', label: '通知', icon: 'Bell' },
  { type: 'subprocess', label: '子流程', icon: 'Folder' },
  { type: 'webhook', label: 'Webhook', icon: 'Link' }
]

// 响应式数据
const elements = ref<any[]>([])
const selectedNode = ref<any>(null)
const selectedApproverType = ref('user')
const showApproverDialog = ref(false)
const showCcDialog = ref(false)
const showRejectTargetDialog = ref(false)

// 面板折叠状态
const leftCollapsed = ref(false)
const rightCollapsed = ref(false)

// 工作流数据
const currentWorkflow = ref<WorkflowDefinition | null>(null)
const users = ref<WorkflowUser[]>([])
const departments = ref<Department[]>([])
const roles = ref<Role[]>([])

// 加载状态
const loading = ref(false)

// Vue Flow 相关
const zoom = ref(1)
const viewport = ref({ x: 0, y: 0 })

// 计算属性
const nodeCount = computed(() => {
  return elements.value.filter((el: any) => !('source' in el)).length
})

const edgeCount = computed(() => {
  return elements.value.filter((el: any) => 'source' in el).length
})

// Vue Flow
const { onConnect: vueFlowOnConnect } = useVueFlow()

// 缩放控制
const zoomIn = () => {
  zoom.value = Math.min(zoom.value + 0.1, 2)
}

const zoomOut = () => {
  zoom.value = Math.max(zoom.value - 0.1, 0.2)
}

const fitView = () => {
  zoom.value = 1
}

// 节点点击事件
const onNodeClick = (event: any) => {
  selectedNode.value = event.node
}

// 删除节点
const deleteNode = async (nodeId: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个节点吗？删除后相关的连线也会被删除。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 删除节点
    elements.value = elements.value.filter(el => el.id !== nodeId)
    
    // 删除与该节点相关的边
    elements.value = elements.value.filter(el => {
      if ('source' in el) {
        return el.source !== nodeId && el.target !== nodeId
      }
      return true
    })
    
    // 如果删除的是当前选中的节点，清空选中状态
    if (selectedNode.value?.id === nodeId) {
      selectedNode.value = null
    }
    
    ElMessage.success('节点删除成功')
  } catch {
    // 用户取消删除
  }
}

// 删除边
const deleteEdge = (edgeId: string) => {
  elements.value = elements.value.filter(el => el.id !== edgeId)
  ElMessage.success('连线删除成功')
}

// 键盘事件处理
const onKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Delete' || event.key === 'Backspace') {
    if (selectedNode.value) {
      deleteNode(selectedNode.value.id)
    }
  }
}

// 删除选中的元素
const deleteSelectedElement = async () => {
  if (selectedNode.value) {
    await deleteNode(selectedNode.value.id)
  }
}

// 切换左侧面板
const toggleLeftPanel = () => {
  leftCollapsed.value = !leftCollapsed.value
}

// 切换右侧面板
const toggleRightPanel = () => {
  rightCollapsed.value = !rightCollapsed.value
}

// 拖拽开始事件
const onDragStart = (event: any, nodeType: any) => {
  event.dataTransfer.setData('application/vueflow', JSON.stringify(nodeType))
}

// 拖拽悬停事件
const onDragOver = (event: any) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

// 拖拽放置事件
const onDrop = (event: any) => {
  event.preventDefault()
  
  const reactFlowBounds = document.querySelector('.workflow-canvas')?.getBoundingClientRect()
  if (!reactFlowBounds) return
  
  const nodeType = JSON.parse(event.dataTransfer.getData('application/vueflow'))
  const position = {
    x: event.clientX - reactFlowBounds.left,
    y: event.clientY - reactFlowBounds.top
  }
  
  const newNode = {
    id: `${nodeType.type}-${Date.now()}`,
    type: nodeType.type,
    position,
    data: {
      name: nodeType.label,
      type: nodeType.type,
      approvers: [],
      ccUsers: [],
      condition: '',
      properties: {},
      // 会签节点默认属性
      jointRule: nodeType.type === 'joint-approval' ? 'all' : undefined,
      // 加签节点默认属性
      addType: nodeType.type === 'add-approval' ? 'before' : undefined,
      // 驳回节点默认属性
      rejectTarget: nodeType.type === 'reject' ? null : undefined
    }
  }
  
  elements.value.push(newNode)
}

// 连接事件
const onConnect = (params: any) => {
  elements.value.push({
    id: `edge-${Date.now()}`,
    source: params.source,
    target: params.target,
    type: 'smoothstep'
  })
}

// 移除审批人
const removeApprover = (approver: any) => {
  if (selectedNode.value?.data?.approvers) {
    const index = selectedNode.value.data.approvers.findIndex((a: any) => a.id === approver.id)
    if (index > -1) {
      selectedNode.value.data.approvers.splice(index, 1)
    }
  }
}

// 移除抄送人
const removeCcUser = (cc: any) => {
  if (selectedNode.value?.data?.ccUsers) {
    const index = selectedNode.value.data.ccUsers.findIndex((c: any) => c.id === cc.id)
    if (index > -1) {
      selectedNode.value.data.ccUsers.splice(index, 1)
    }
  }
}

// 移除驳回目标
const removeRejectTarget = () => {
  if (selectedNode.value?.data) {
    selectedNode.value.data.rejectTarget = null
  }
}

// 审批人选择确认
const onApproverSelected = (approvers: any[]) => {
  if (selectedNode.value?.data) {
    if (!selectedNode.value.data.approvers) {
      selectedNode.value.data.approvers = []
    }
    selectedNode.value.data.approvers.push(...approvers)
  }
  showApproverDialog.value = false
}

// 抄送人选择确认
const onCcSelected = (ccUsers: any[]) => {
  if (selectedNode.value?.data) {
    if (!selectedNode.value.data.ccUsers) {
      selectedNode.value.data.ccUsers = []
    }
    selectedNode.value.data.ccUsers.push(...ccUsers)
  }
  showCcDialog.value = false
}

// 驳回目标选择确认
const onRejectTargetSelected = (targetNode: any) => {
  if (selectedNode.value?.data) {
    selectedNode.value.data.rejectTarget = {
      id: targetNode.id,
      name: targetNode.data?.name || targetNode.id,
      type: targetNode.data?.type
    }
  }
  showRejectTargetDialog.value = false
}

// 保存流程
const saveWorkflow = async () => {
  if (elements.value.length === 0) {
    ElMessage.warning('请先添加流程节点')
    return
  }
  
  await saveWorkflowToBackend()
}

// 加载流程
const loadWorkflow = async () => {
  await loadWorkflowFromBackend()
}

// 清空画布
const clearCanvas = () => {
  elements.value = []
  selectedNode.value = null
}

// 预览流程
const previewWorkflow = () => {
  console.log('预览流程:', elements.value)
}

// 导出流程
const exportWorkflow = () => {
  const workflowData = {
    name: '工作流程',
    description: '流程描述',
    steps: elements.value
      .filter(el => el.type === undefined) // 只取节点，不取边
      .map((node, index) => ({
        id: node.id,
        name: node.data?.name || `节点${index + 1}`,
        type: node.data?.type || 'approval',
        order: index + 1,
        approvers: node.data?.approvers?.map((a: any) => a.id) || [],
        ccUsers: node.data?.ccUsers?.map((c: any) => c.id) || [],
        condition: node.data?.condition || '',
        properties: node.data?.properties || {}
      }))
  }
  
  const dataStr = JSON.stringify(workflowData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'workflow.json'
  link.click()
  URL.revokeObjectURL(url)
}

// 验证流程
const validateWorkflow = () => {
  const nodes = elements.value.filter(el => !('source' in el))
  
  if (nodes.length === 0) {
    return { isValid: false, message: '请至少添加一个流程节点' }
  }
  
  // 检查是否有开始节点
  const startNodes = nodes.filter(node => node.data?.type === 'start')
  if (startNodes.length === 0) {
    return { isValid: false, message: '请添加开始节点' }
  }
  
  if (startNodes.length > 1) {
    return { isValid: false, message: '只能有一个开始节点' }
  }
  
  // 检查是否有结束节点
  const endNodes = nodes.filter(node => node.data?.type === 'end')
  if (endNodes.length === 0) {
    return { isValid: false, message: '请添加结束节点' }
  }
  
  // 检查审批节点是否有审批人
  const approvalNodes = nodes.filter(node => 
    ['approval', 'joint-approval', 'add-approval'].includes(node.data?.type || '')
  )
  
  for (const node of approvalNodes) {
    if (!node.data?.approvers || node.data.approvers.length === 0) {
      return { isValid: false, message: `节点 "${node.data?.name}" 需要设置审批人` }
    }
  }
  
  // 检查条件节点是否有条件表达式
  const conditionNodes = nodes.filter(node => node.data?.type === 'condition')
  for (const node of conditionNodes) {
    if (!node.data?.condition || node.data.condition.trim() === '') {
      return { isValid: false, message: `节点 "${node.data?.name}" 需要设置条件表达式` }
    }
  }
  
  return { isValid: true, message: '' }
}

// 获取 Workflow-Core 步骤类型
const getWorkflowStepType = (nodeType: string) => {
  const typeMap: Record<string, string> = {
    'start': 'StartStep',
    'approval': 'ApprovalStep',
    'joint-approval': 'JointApprovalStep',
    'add-approval': 'AddApprovalStep',
    'reject': 'RejectStep',
    'condition': 'ConditionStep',
    'end': 'EndStep'
  }
  return typeMap[nodeType] || 'ApprovalStep'
}

// 从后端加载流程
const loadWorkflowFromBackend = async () => {
  try {
    loading.value = true
    
    // 这里可以添加流程选择对话框
    const response = await WorkflowApiService.getWorkflowDefinitions()
    
    if (response.success && response.data && response.data.length > 0) {
      // 选择第一个流程作为示例
      const workflow = response.data[0]
      await loadWorkflowDefinition(workflow.id)
    } else {
      ElMessage.warning('没有可用的流程定义')
    }
  } catch (error) {
    console.error('加载流程失败:', error)
    ElMessage.error('加载流程失败')
  } finally {
    loading.value = false
  }
}

// 加载指定的流程定义
const loadWorkflowDefinition = async (id: string) => {
  try {
    const response = await WorkflowApiService.getWorkflowDefinition(id)
    
    if (response.success && response.data) {
      currentWorkflow.value = response.data
      
      // 转换步骤为流程元素
      const flowElements: any[] = []
      
      response.data.steps.forEach((step, index) => {
        // 创建节点
        const node: any = {
          id: step.id,
          type: step.type,
          position: step.position || { x: index * 200, y: 100 },
          data: {
            name: step.name,
            type: step.type,
            approvers: step.approvers.map(id => users.value.find(u => u.id === id)).filter(Boolean) as WorkflowUser[],
            ccUsers: step.ccUsers.map(id => users.value.find(u => u.id === id)).filter(Boolean) as WorkflowUser[],
            condition: step.condition,
            properties: step.properties,
            jointRule: step.properties?.jointRule,
            addType: step.properties?.addType,
            rejectTarget: step.properties?.rejectTarget
          }
        }
        
        flowElements.push(node)
        
        // 创建连接边
        if (index > 0) {
          const edge: any = {
            id: `edge-${step.id}`,
            source: response.data!.steps[index - 1].id,
            target: step.id,
            type: 'smoothstep'
          }
          flowElements.push(edge)
        }
      })
      
      elements.value = flowElements
      ElMessage.success('流程加载成功')
    } else {
      ElMessage.error('加载流程失败')
    }
  } catch (error) {
    console.error('加载流程定义失败:', error)
    ElMessage.error('加载流程定义失败')
  }
}

// 保存流程到后端
const saveWorkflowToBackend = async () => {
  try {
    loading.value = true
    
    // 验证流程
    const validationResult = validateWorkflow()
    if (!validationResult.isValid) {
      ElMessage.error(validationResult.message)
      return
    }
    
    // 转换流程数据为 Workflow-Core 兼容格式
    const steps: WorkflowStep[] = elements.value
      .filter(el => !('source' in el)) // 只取节点，不取边
      .map((node, index) => ({
        id: node.id,
        name: node.data?.name || `节点${index + 1}`,
        type: node.data?.type || 'approval',
        order: index + 1,
        approvers: node.data?.approvers?.map((a: WorkflowUser) => a.id) || [],
        ccUsers: node.data?.ccUsers?.map((c: WorkflowUser) => c.id) || [],
        condition: node.data?.condition || '',
        properties: {
          ...node.data?.properties,
          jointRule: node.data?.jointRule,
          addType: node.data?.addType,
          rejectTarget: node.data?.rejectTarget,
          // Workflow-Core 特定属性
          workflowStepType: getWorkflowStepType(node.data?.type),
          stepId: node.id,
          position: node.position
        }
      }))

    const request: CreateWorkflowRequest = {
      name: currentWorkflow.value?.name || '新流程',
      description: currentWorkflow.value?.description || '流程描述',
      steps
    }

    const response = await WorkflowApiService.createWorkflowDefinition(request)
    
    if (response.success && response.data) {
      ElMessage.success('流程保存成功')
      currentWorkflow.value = response.data
      emit('save', response.data)
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存流程失败:', error)
    ElMessage.error('保存流程失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(async () => {
  await loadInitialData()
})

// 加载初始数据
const loadInitialData = async () => {
  try {
    loading.value = true
    const [usersRes, departmentsRes, rolesRes] = await Promise.all([
      WorkflowApiService.getUsers(),
      WorkflowApiService.getDepartments(),
      WorkflowApiService.getRoles()
    ])
    
    if (usersRes.success && usersRes.data) users.value = usersRes.data
    if (departmentsRes.success && departmentsRes.data) departments.value = departmentsRes.data
    if (rolesRes.success && rolesRes.data) roles.value = rolesRes.data
  } catch (error) {
    console.error('加载初始数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

defineOptions({
  name: 'WorkflowDesigner'
})
</script>

<style scoped>
.workflow-designer {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.toolbar {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.toolbar .el-button {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.toolbar .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.toolbar .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.toolbar .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
}

.main-content {
  display: flex;
  flex: 1;
  min-height: 0;
}

.toolbox {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  padding: 24px;
  overflow-y: auto;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.toolbox.collapsed {
  width: 60px;
  padding: 12px;
}

.toolbox-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
  position: relative;
}

.toolbox-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.collapse-btn {
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background: #e6f7ff;
  color: #409eff;
}

.toolbox-content {
  transition: all 0.3s ease;
}

.toolbox h3 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
  position: relative;
}

.toolbox h3::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 40px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
}

.node-category h4 {
  margin: 20px 0 12px 0;
  font-size: 15px;
  color: #606266;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.node-category h4::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(180deg, #409eff, #67c23a);
  margin-right: 8px;
  border-radius: 2px;
}

.node-types {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.node-item {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: grab;
  background: #ffffff;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.node-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(64, 158, 255, 0.1), transparent);
  transition: left 0.5s ease;
}

.node-item:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
  color: #409eff;
}

.node-item:hover::before {
  left: 100%;
}

.node-item:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.node-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409eff;
  transition: all 0.3s ease;
}

.node-item:hover .el-icon {
  color: #409eff;
  transform: scale(1.1);
}

.approver-types {
  margin-top: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.approver-types h3 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.approver-types .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.approver-types .el-radio {
  margin: 0;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.approver-types .el-radio:hover {
  background: #e6f7ff;
}

.approver-types .el-radio.is-checked {
  background: #e6f7ff;
  color: #409eff;
}

.canvas-area {
  flex: 1;
  position: relative;
}

.workflow-canvas {
  width: 100%;
  height: 100%;
}

.properties-area {
  width: 320px;
  border-left: 1px solid #e4e7ed;
  padding: 24px;
  overflow-y: auto;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.properties-area.collapsed {
  width: 60px;
  padding: 12px;
}

.properties-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
  position: relative;
}

.properties-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.properties-content {
  transition: all 0.3s ease;
}

.properties-area h3 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
  position: relative;
}

.properties-area h3::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 40px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
}

.node-properties {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.node-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.delete-btn {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.node-properties .el-form-item {
  margin-bottom: 20px;
}

.node-properties .el-form-item__label {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.node-properties .el-input,
.node-properties .el-select,
.node-properties .el-textarea {
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.node-properties .el-input:focus,
.node-properties .el-select:focus,
.node-properties .el-textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.node-properties .el-button {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.node-properties .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.approver-list,
.cc-list,
.reject-target {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.approver-list .el-tag,
.cc-list .el-tag,
.reject-target .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  border: 1px solid #b3d8ff;
  color: #409eff;
}

.approver-list .el-tag:hover,
.cc-list .el-tag:hover,
.reject-target .el-tag:hover {
  background: linear-gradient(135deg, #d1ecff 0%, #e6f7ff 100%);
  border-color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
}

.approver-list .el-tag .el-icon-close,
.cc-list .el-tag .el-icon-close,
.reject-target .el-tag .el-icon-close {
  color: #409eff;
  font-size: 12px;
  margin-left: 4px;
}

.approver-list .el-tag .el-icon-close:hover,
.cc-list .el-tag .el-icon-close:hover,
.reject-target .el-tag .el-icon-close:hover {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
  border-radius: 50%;
}

.no-selection {
  text-align: center;
  color: #909399;
  padding: 60px 20px;
  background: #ffffff;
  border-radius: 8px;
  border: 2px dashed #e4e7ed;
  margin: 20px 0;
  transition: all 0.3s ease;
}

.no-selection:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.no-selection p {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  color: #606266;
}

.delete-tips {
  margin-top: 20px;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
}

.delete-tips p {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.delete-tips ul {
  margin: 0;
  padding-left: 20px;
}

.delete-tips li {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
  line-height: 1.4;
}

/* 单选框组美化 */
.node-properties .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.node-properties .el-radio {
  margin: 0;
  padding: 10px 14px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  background: #ffffff;
  transition: all 0.3s ease;
}

.node-properties .el-radio:hover {
  background: #f0f9ff;
  border-color: #409eff;
}

.node-properties .el-radio.is-checked {
  background: #e6f7ff;
  border-color: #409eff;
  color: #409eff;
}

.node-properties .el-radio__label {
  font-weight: 500;
  color: #606266;
}

.node-properties .el-radio.is-checked .el-radio__label {
  color: #409eff;
}

.status-bar {
  padding: 12px 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.status-bar span {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.status-bar span:hover {
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}
</style> 